//import angular core
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

//import third package
import 'rxjs/add/operator/switchMap';

//import service
import { FoodService } from '../../service/food.service';

//import class
import { Food } from '../../domain/food';

@Component({
  selector: 'app-food-detail',
  templateUrl: './food-detail.component.html',
  styleUrls: ['./food-detail.component.css'],
  providers: [FoodService]
})
export class FoodDetailComponent implements OnInit {

  food: Food;
  foodUpdate: Food;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private foodService: FoodService,
    private location: Location
  ) { }

  ngOnInit() {
    this.route.params
      .switchMap((params: Params) => this.foodService.getFoodById(+params['id']))
      .subscribe(res => {
        this.food = res;
        this.foodUpdate = res;
      });
  }

  updateFood(): void {
    this.foodService.updateFood(this.foodUpdate)
    .then(()=>{
      this.goBack();
    })
  }

  reset(): void {
    this.foodUpdate = this.food;
  }

  goBack(): void {
    this.location.back();
  }
}
